package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.PlaneInfoEntityBuilder;
import com.foreveross.crawl.adapter.sub.impl20140402.v3.britishairways.BritishairwaysInernationRoundTrip;
import com.foreveross.crawl.common.exception.self.SourceDataParseNullException;
import com.foreveross.crawl.common.exception.self.UnableParseRouteTypeException;
import com.foreveross.crawl.domain.airfreight.CabinEntity;
import com.foreveross.crawl.domain.airfreight.doub.CabinRelationEntity;
import com.foreveross.crawl.domain.airfreight.doub.DoublePlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnCabinEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnDoublePlaneInfoEntity;
import com.foreveross.crawl.util.DateUtil;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;

/**
 * 英国航空公司
 * @author luofangyi
 *
 */
public class BritishairwaysAdapter extends AbstractAdapter {

	public Map<String, String> cabinMap = new HashMap<String, String>();
//	public Map<String, String> numberMap = new HashMap<String, String>();
	public final int GO = 0;//去程
	public final int BACK = 1;//回程
	public boolean isGrab = true;//是否抓取税费
	public final Integer ECONOMY = 8;//经济舱
	public final Integer WORLDTRAVELLERPLUS = 7;//高级经济舱
	public final Integer BUSINESS = 9;//公务舱
	
	public BritishairwaysAdapter(TaskModel taskQueue) {
		super(taskQueue);
		cabinMap.put("M", "Economy");//经济舱
		cabinMap.put("W", "World Traveller Plus");//高级经济客舱
		cabinMap.put("J", "Business/Club");//公务客舱
		cabinMap.put("F", "First");//头等客舱
//		assginNumberMap();
		//暂时不开发该功能
//		try {
//			this.isGrab = PropertyUtils.getBooleanProperty(EnginePropertiesLoader.ENGINE_CHANNEL_TASK_CRAWL_TAX_BRITISHAIRWAYSADAPTER, EnginePropertiesLoader.FILE_NAME);
//		} catch (Exception e) {
//			this.isGrab = true;
//		}
	}
	
//	public void assginNumberMap(){
//		numberMap.put("一", "1");
//		numberMap.put("二", "2");
//		numberMap.put("三", "3");
//		numberMap.put("四", "4");
//		numberMap.put("五", "5");
//		numberMap.put("六", "6");
//		numberMap.put("七", "7");
//		numberMap.put("八", "8");
//		numberMap.put("九", "9");
//		numberMap.put("十", "10");
//		numberMap.put("十一", "11");
//		numberMap.put("十二", "12");
//	}

	@Override
	@Deprecated
	public String getUrl() throws Exception {
		return null;
	}

	@Override
	public Object fetch(String url) throws Exception {
		switch (getRouteType()) {
		case DOMESTIC_ONEWAYTRIP:
			throw new UnableParseRouteTypeException(taskQueue,getRouteType().getName());
		case DOMESTIC_ROUNDTRIP:
			throw new UnableParseRouteTypeException(taskQueue,getRouteType().getName());
		case INTERNATIONAL_ONEWAY:
			throw new UnableParseRouteTypeException(taskQueue, getRouteType().getName());
		case INTERNATIONAL_ROUND:
			return new BritishairwaysInernationRoundTrip(this, taskQueue).fetchData();
		}
		return null;
	}

	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		if(fetchObject == null){
			throw new SourceDataParseNullException("没有抓取到数据");
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		
		return (List<Object>)fetchObject;
	}

	/**
	 * 使WebClient对象具有自动跳转及js执行能力
	 * @param webClient
	 */
	public void hasWebClientRedirectEnabled(WebClient webClient){

		webClient.getOptions().setRedirectEnabled(true);
		webClient.getOptions().setJavaScriptEnabled(true);
		webClient.getOptions().setActiveXNative(false);
		webClient.getOptions().setCssEnabled(false);
		webClient.getOptions().setThrowExceptionOnScriptError(false);
		webClient.setAjaxController(new NicelyResynchronizingAjaxController());
	}
	
	public String getPatternString(String content, String regEx){
		Pattern p=Pattern.compile(regEx, Pattern.DOTALL|Pattern.MULTILINE);
		Matcher m=p.matcher(content);
		String retStr = "";
		if(m.find()){
			retStr=  m.group(1);
		}
		return retStr.trim().replaceAll("\t", "").replaceAll("\n", "");
	}
	
	/**
	 * 将类似：星期一 15 September 2014, 11:15 格式字符串转换成Date
	 * @param str
	 * @param dateFormat
	 * @return
	 * @throws ParseException
	 */
	public Date convertStrToDate(String str) throws ParseException{
		str = str.substring(str.indexOf(" ")).trim();
		return DateUtil.string2Date(str, "dd MMMM yyyy, hh:mm", Locale.US);
	}
	
	/**
	 * 将类似：10hrs 55mins 或  55mins 转换成Long类型
	 * @param str
	 * @return
	 */
	public static Long convertStrToLong(String str){
//		Long hour = 0L;
//		Long mins = 0L;
//		if(str.contains("hrs")){
//			hour = Long.parseLong(str.substring(0, str.indexOf("hrs")).trim()) * 1000 * 60;
//		}
//		if(str.contains("mins") && str.contains("hrs")){
//			mins = Long.parseLong(str.substring(str.indexOf(" "), str.indexOf("mins")).trim()) * 1000;
//		} else if(str.contains("mins")){
//			mins = Long.parseLong(str.substring(0, str.indexOf("mins")).trim());
//		}
//		
//		return hour + mins;
		Long time = null;
		Pattern pattern = Pattern.compile("\\d+");
		Matcher matcher = pattern.matcher(str);
		List<String> timeList = new ArrayList<String>();
		while (matcher.find()) {
			timeList.add(matcher.group(0));
		}
		if(timeList.size() == 1){
			time = Long.parseLong(timeList.get(0)) * 60 * 1000;//分
		} else if(timeList.size() == 2){
			time = Long.parseLong(timeList.get(0)) * 60 * 60 * 1000;//时
			time += Long.parseLong(timeList.get(1)) * 60 * 1000;//分
		}
		return time;
	}
	
	/**
	 * 除字符串中的空格、回车、换行符、制表符
	 * @param target
	 * @return
	 */
	public String replaceSpecialCharacters(String target){
		String dest = "";
        if (target!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(target);
            dest = m.replaceAll("");
        }
        return dest;
	}
	
	public List<DoublePlaneInfoEntity> dealToEntityAndReturnEntity(List<DoublePlaneInfoEntity> toEntity){
		
		List<DoublePlaneInfoEntity> retList = new ArrayList<DoublePlaneInfoEntity>();
		for(DoublePlaneInfoEntity to : toEntity){
			Set<CabinEntity> toCabinSet = to.getCabins();
			Set<ReturnDoublePlaneInfoEntity> retEntitySet = to.getReturnPlaneInfos();
			for(ReturnDoublePlaneInfoEntity retEntity : retEntitySet){
				//最低
				Set<ReturnCabinEntity> retCabinSet = retEntity.getReturnCabins();
				to.getCabinRelations().addAll(this.dealToAndReturnCainbRelationEntity(toCabinSet, retCabinSet));
			}
			List<CabinRelationEntity> relationList = this.setToList(to.getCabinRelations());
			PlaneInfoEntityBuilder.orderByPrice(relationList);//升序
			to.setTotalLowestPrice(relationList.get(0).getFullPrice());
			retList.add(to);
		}
//		this.setLowestOfReturnDoublePlaneInfoEntity(retList);
		return retList;
	}
	
	/**
	 * 设置回程最低价
	 * @param toEntity
	 */
	private void setLowestOfReturnDoublePlaneInfoEntity(List<DoublePlaneInfoEntity> toEntity){
		for(DoublePlaneInfoEntity to : toEntity){
			for(ReturnDoublePlaneInfoEntity retEntity : to.getReturnPlaneInfos()){
				retEntity.setTotalLowestPrice(to.getTotalLowestPrice());
			}
		}
	}
	
	private List<CabinRelationEntity> setToList(Set<CabinRelationEntity> relationSet){
		Iterator<CabinRelationEntity> iter = relationSet.iterator();
		List<CabinRelationEntity> list = new ArrayList<CabinRelationEntity>();
		while(iter.hasNext()){
			list.add(iter.next());
		}
		return list;
	}
	
	public Set<CabinRelationEntity> dealToAndReturnCainbRelationEntity(Set<CabinEntity> toCabinSet, Set<ReturnCabinEntity> retCabinSet){
		Set<CabinRelationEntity> set = new HashSet<CabinRelationEntity>();
		for(CabinEntity toCabin : toCabinSet){
			toCabin.setTaxesPrice(toCabin.getTaxesPrice());
			//此适配器暂时只取一个
			for(ReturnCabinEntity retCabin : retCabinSet){
				CabinRelationEntity relationEntity = new CabinRelationEntity();
				relationEntity.setCabinId(toCabin.getId());
				//预处理的税价，从回程舱位里拿的
				relationEntity.setTaxesPrice(retCabin.getTaxesPrice());
				relationEntity.setFullPrice(toCabin.getPrice() + retCabin.getPrice());
				relationEntity.setTotalFullPrice((relationEntity.getFullPrice()!=null?relationEntity.getFullPrice():0.0)+(relationEntity.getTaxesPrice()!=null?relationEntity.getTaxesPrice():0.0));
				relationEntity.setReturnCabinId(retCabin.getId());
				set.add(relationEntity);
			}
		}
		return set;
	}
	
	public static void main(String[] args) throws Exception{
		TaskModel taskQueue = new TaskModel();
		taskQueue.setIsInternational(1);
		taskQueue.setIsReturn(1);
		taskQueue.setProxyIp("1");
//		taskQueue.setFlightDate("30/09/14");
//		taskQueue.setReturnGrabDate("29/10/14");
		taskQueue.setFlightDate("2015-01-03");
		taskQueue.setReturnGrabDate("2015-10-10");
		taskQueue.setIsInternational(1);
		taskQueue.setIsReturn(1);
		taskQueue.setFromCityName("北京");
		taskQueue.setToCityName("伦敦");
		taskQueue.setFromCity("PEK");
		taskQueue.setToCity("LHR");
		BritishairwaysAdapter ba = new BritishairwaysAdapter(taskQueue);
		List<Object> objs = ba.paraseToVo(ba.fetch(null));
		ba.printJson(objs, "f:/ba.txt");
	}
}
